﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace Adams.Web.Data.Sitemap
{
    public static class Index
    {
        public static Adams.Web.Models.Sitemap.Index.PageLoad PageLoad()
        {
            var data = new Adams.Web.Models.Sitemap.Index.PageLoad();
            var nodes = new Shared.Entities.Sitemap.NodeCollection();

            using (SqlDataReader dr = DB.RunDataReader(@"
-- Top Nodes
WITH AllNodes AS (
	SELECT n.NodeID, n.ParentNodeID, n.DisplayOrder, 0 AS [Level], n.Title, n.Url
	FROM Sitemap.Nodes n
	WHERE NodeID = 1
	UNION ALL
	SELECT n.NodeID, n.ParentNodeID, n.DisplayOrder, a.[Level] + 1, n.Title, n.Url
	FROM Sitemap.Nodes n JOIN AllNodes a ON n.ParentNodeID = a.NodeID 
)
SELECT * 
FROM AllNodes
ORDER BY Level, DisplayOrder;
", CommandType.Text))
            {
                while (dr.Read())
                {
                    var node = DB.InitFromReader<Shared.Entities.Sitemap.Node>(dr, new ColMap { NameInDb = "NodeID", NameInObject = "ID" }); ;
                    node.ParentNode = new Shared.Entities.Sitemap.Node()
                    {
                        ID = dr["ParentNodeID"].DbInt()
                    };
                    node.ChildNodes = new Shared.Entities.Sitemap.NodeCollection();
                    nodes.Add(node);
                }

                foreach (var node in nodes)
                {
                    if (node.ID == 1)
                    {
                        data.Node = node;
                    }
                    else
                    {
                        nodes.Where(n => n.ID == node.ParentNode.ID).FirstOrDefault().ChildNodes.Add(node);
                    }
                }
            }

            return data;
        }
    }
}